#!/bin/sh

. ${WORLDDIR}/release/tools/ec2.conf

# Build with a 7.9 GB partition; this is enough for our stripped-down
# base system plus the compressed ec2-base image.
export VMSIZE=8000m

# Flags to installworld/kernel: We don't want debug symbols (kernel or
# userland), 32-bit libraries, or tests.
export INSTALLOPTS="WITHOUT_DEBUG_FILES=YES WITHOUT_KERNEL_SYMBOLS=YES \
    WITHOUT_LIB32=YES WITHOUT_TESTS=YES"

# Equivalent to INSTALLOPTS for pkgbase
vm_extra_filter_base_packages() {
	grep -v \
		-e '.*-dbg$' \
		-e '.*-lib32$' \
		-e '^FreeBSD-set-tests'
}

# Packages to install into the image we're creating.  In addition to packages
# present on all EC2 AMIs, we install:
# * ec2-scripts, which provides a range of EC2ification startup scripts,
# * isc-dhcp44-client, used for IPv6 network setup, and
# * py-awscli, to make it easier for users to create AMIs.
export VM_EXTRA_PACKAGES="${VM_EXTRA_PACKAGES} ec2-scripts \
    isc-dhcp44-client devel/py-awscli"

# Services to enable in rc.conf(5).
export VM_RC_LIST="${VM_RC_LIST} ec2_configinit ec2_ephemeral_swap \
    ec2_fetchkey ec2_loghostkey sshd"

vm_extra_pre_umount() {
	# Any EC2 ephemeral disks seen when the system first boots will
	# be "new" disks; there is no "previous boot" when they might have
	# been seen and used already.
	touch ${DESTDIR}/var/db/ec2_ephemeral_diskseen
	metalog_add_data ./var/db/ec2_ephemeral_diskseen

	# Configuration common to all EC2 AMIs
	ec2_common

	# Standard FreeBSD network configuration
	ec2_base_networking

	# Grab a copy of the ec2-base disk image, and compress it
	zstd < ${EC2BASEIMG} > ${DESTDIR}/image.zst
	metalog_add_data ./image.zst

	# Disable fortune so we don't have extra noise at login
	chmod a-x ${DESTDIR}/usr/bin/fortune

	# Install the AMI-building script
	install -m 755 ${WORLDDIR}/release/tools/mkami.sh ${DESTDIR}/bin/mkami
	metalog_add_data ./bin/mkami 0755

	# Install an /etc/rc which juggles disks around for us
	install -m 755 ${WORLDDIR}/release/tools/rc.amibuilder ${DESTDIR}/etc
	metalog_add_data ./etc/rc.amibuilder 0755

	# We want to mount from the UFS disk and juggle disks first
	cat >> ${DESTDIR}/boot/loader.conf <<-EOF
		vfs.root.mountfrom="ufs:/dev/gpt/rootfs"
		init_script="/etc/rc.amibuilder"
	EOF
	metalog_add_data ./boot/loader.conf

	# Add files from packages which weren't recorded in metalog
	metalog_add_data ./usr/local/etc/dhclient.conf

	return 0
}
